package com.nuumoblie.bluetoothtools.bt

import android.Manifest
import android.bluetooth.BluetoothA2dp
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothHeadset
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import es.dmoral.toasty.Toasty

class BtManager(val mContext: Context, val callback: Callback?) : BroadcastReceiver() {

    val mBtAdapter: BluetoothAdapter by lazy { BluetoothAdapter.getDefaultAdapter(); }
    val mBtOptClient: BtOptClient by lazy { BtOptClient(callback); }

    init {
        register();
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        var action = intent?.action;
        if (action == null) {
            return;
        }
        Log.i("lmjssjj", "===$action")
        val device = intent?.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
        if (device != null)
            Log.i("lmjssjj", "BluetoothDevice: " + device.name + ", " + device.address)

        when (action) {
            BluetoothAdapter.ACTION_STATE_CHANGED -> {
            };

            BluetoothAdapter.ACTION_DISCOVERY_STARTED -> {
                callback?.scanStart();
            };
            BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                callback?.discoveryFinish()
            };

            BluetoothDevice.ACTION_FOUND -> {
                val rssi =
                    intent?.getShortExtra(BluetoothDevice.EXTRA_RSSI, java.lang.Short.MAX_VALUE)
                Log.i("lmjssjj", "EXTRA_RSSI:$rssi")
                callback?.foundDevice(device);
            };

            BluetoothDevice.ACTION_PAIRING_REQUEST -> {
            };//在系统弹出配对框之前，实现自动配对，取消系统配对框
            BluetoothDevice.ACTION_BOND_STATE_CHANGED -> {
            };

            BluetoothDevice.ACTION_ACL_CONNECTED -> {
            };
            BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
            };

            BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED -> {
            };

            BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED -> {
            };

            BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED -> {
            };
            else -> {
            };
        }
    }

    fun register(): Unit {
        val filter = IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)//蓝牙开关状态
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)//蓝牙开始搜索
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)//蓝牙搜索结束

        filter.addAction(BluetoothDevice.ACTION_FOUND)//蓝牙发现新设备(未配对的设备)
        filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)//在系统弹出配对框之前(确认/输入配对码)
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)//设备配对状态改变
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED)//最底层连接建立
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)//最底层连接断开

        filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED) //BluetoothAdapter连接状态
        filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED) //BluetoothHeadset连接状态
        filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED) //BluetoothA2dp连接状态

        mContext.registerReceiver(this, filter);
    }

    fun unRegister(): Unit {
        mContext.unregisterReceiver(this)
    }

    fun isConnected(device: BluetoothDevice?): Boolean {
        return mBtOptClient.isConnected(device);
    }

    fun disconnect(device: BluetoothDevice?){
        if (isConnected(device)){
            mBtOptClient.close();
        }
    }

    fun scan(): Unit {

        if (mBtAdapter.isEnabled) {

            if (mBtAdapter.isDiscovering) {
                Toasty.warning(mContext, "正在扫描", Toast.LENGTH_SHORT).show();
            } else {
                mBtAdapter.startDiscovery();
            }

        } else {
            Toasty.warning(mContext, "请先打开蓝牙", Toast.LENGTH_SHORT).show();
        }
    }

    fun cancelDiscovery() {
        if (mBtAdapter.isDiscovering)
            mBtAdapter.cancelDiscovery();
    }

    fun connect(device: BluetoothDevice?,isMatch :Boolean) {
        mBtOptClient.connect(device,isMatch);
    }

    fun sendFile(path: String?,isVerify:Boolean) {
        mBtOptClient.sendFile(path,isVerify);
    }

    fun sendMsg(msg:String){
        mBtOptClient.sendMsg(msg);
    }

    fun getBondedDevices(): MutableSet<BluetoothDevice>? {
        return mBtAdapter.bondedDevices;
    }

    public interface Callback : BtOptBase.Listener {
        fun scanStart();
        fun foundDevice(device: BluetoothDevice?);
        fun discoveryFinish();
    }

}